<template>
  <div>
    <div class="head">
      <van-nav-bar>
        <template #left>
          <div class="logo">
            <img src="@/assets/images/home_active.png" alt="" />
            <span class="logo-title">Luckin Coffee</span>
          </div>
        </template>
        <template #right>
          <div class="goBefore" @click="methods.goLook">先逛一逛</div>
        </template>
      </van-nav-bar>
    </div>
    <div class="login-box">
      <h1 class="login-title">欢迎回来</h1>
      <p class="login-subTitle">Please login to your accounts</p>
      <van-form @submit="methods.onLogin">
        <van-field
          v-model="phone"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[
            {
              required: true,
              message: '请填写正确手机号',
              pattern: /^1[3-9][0-9]{9}$/
            }
          ]"
          type="digit"
        />
        <van-field
          v-model="password"
          :type="isHidden ? 'text' : 'password'"
          name="密码"
          label="密码"
          placeholder="密码"
          :right-icon="isHidden ? 'eye-o' : 'closed-eye'"
          @click-right-icon="methods.isPassword"
          :rules="[
            {
              required: true,
              message: '必须以字母开头,6-16位字母数字下划线组合',
              pattern: /^[A-Za-z]\w{5,15}$/
            }
          ]"
        />
        <div class="login-tip">
          <span @click="methods.goForgetPassword">忘记密码?</span>
        </div>
        <div style="margin: 16px">
          <van-button
            round
            block
            type="primary"
            native-type="submit"
            color="rgb(12,52,186)"
          >
            登录
          </van-button>
        </div>
      </van-form>
      <div style="margin: 40px 16px 16px">
        <van-button @click="methods.showPopup" round block type="default">
          注册
        </van-button>
      </div>

      <van-popup closeable v-model:show="isShowRegister" position="bottom">
        <div class="popup-title">注册</div>
        <van-form @submit="methods.onRegister">
          <van-field
            v-model="registerPhone"
            name="手机号"
            label="手机号"
            placeholder="手机号"
            :rules="[
              {
                required: true,
                message: '请填写正确手机号',
                pattern: /^1[3-9][0-9]{9}$/
              }
            ]"
          />
          <van-field
            v-model="registerPassword"
            :type="isHidden2 ? 'text' : 'password'"
            name="密码"
            label="密码"
            placeholder="密码"
            :right-icon="isHidden2 ? 'eye-o' : 'closed-eye'"
            @click-right-icon="methods.isPassword2"
            :rules="[
              {
                required: true,
                message: '必须以字母开头,6-16位字母数字下划线组合',
                pattern: /^[A-Za-z]\w{5,15}$/
              }
            ]"
          />
          <van-field
            v-model="nickname"
            type="text"
            name="昵称"
            label="昵称"
            placeholder="请输入昵称"
            :rules="[
              {
                required: true,
                message: '请填写昵称'
              }
            ]"
          />
          <div style="margin: 40px 16px 16px">
            <van-button
              round
              block
              type="primary"
              native-type="submit"
              color="rgb(12,52,186)"
            >
              注册
            </van-button>
          </div>
        </van-form>
      </van-popup>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { postFormData } from '@/api'
import { useRouter } from 'vue-router'
import { setToken } from '@/utils/token'
import { useUserStore } from '@/store'
import { encryptPassword } from '@/utils/crypto'
const userStore = useUserStore()

const phone = ref<number | undefined>()
const password = ref('')
const registerPhone = ref('')
const registerPassword = ref('')
const isHidden = ref(false)
const isHidden2 = ref(false)
/** 是否显示注册弹窗 */
const isShowRegister = ref(false)
const nickname = ref('')

const router = useRouter()
const methods = {
  onLogin(values: Record<string, any>) {
    // const salt = generateSalt() // 前端生成动态盐值
    const encryptedPwd = encryptPassword(values['密码'])
    const phoneNumber = values['手机号']
    const obj = {
      password: encryptedPwd,
      phone: phoneNumber
      // salt
    }
    postFormData({
      url: '/auth/login',
      params: obj
    })
      .then((res) => {
        if (res.code === 200) {
          showSuccessToast(res.message)
          // sessionStorage.setItem('userToken', res.data.token)
          // sessionStorage.setItem('isLogin', 'true')
          setToken(res.data.token)
          userStore.setUserInfo(res.data.userInfo)
          router.push({ name: 'Home' })
        } else {
          showToast({
            message: res.msg,
            forbidClick: true
          })
          phone.value = undefined
          password.value = ''
        }
      })
      .catch((err) => {
        console.error(err)
      })
  },
  /**
   * 处理用户注册逻辑。
   * @param {Record<string, any>} values - 包含用户注册信息的对象，键为字段名（如"昵称"、"密码"、"手机号"），值为用户输入的值。
   * @description
   * - 从输入值中提取昵称、密码和手机号。
   * - 构造请求对象，包含固定的appkey和用户输入的信息。
   * - 发送注册请求到后端接口。
   * - 注册成功时关闭注册弹窗，清空输入框，并显示成功提示。
   * - 注册失败时打印错误信息。
   */
  onRegister(values: Record<string, any>) {
    const nickName = values['昵称']
    const phone = values['手机号']
    // const salt = generateSalt() // 前端生成动态盐值
    const encryptedPwd = encryptPassword(values['密码'])
    const obj = {
      username: nickName,
      password: encryptedPwd,
      phone
      // salt
    }
    postFormData({
      url: '/auth/register',
      params: obj
    })
      .then((res) => {
        if (res.code === 201) {
          isShowRegister.value = false
          showSuccessToast('注册成功')
        }
        registerPassword.value = ''
        registerPhone.value = ''
        nickname.value = ''
      })
      .catch((err) => {
        console.error(err)
      })
  },
  isPassword() {
    isHidden.value = !isHidden.value
  },
  isPassword2() {
    isHidden2.value = !isHidden2.value
  },
  showPopup() {
    isShowRegister.value = true
    console.log({ isShowRegister: isShowRegister.value })
  },
  goLook() {
    router.push({ name: 'Home' })
  },
  goForgetPassword() {
    router.push({ name: 'ForgetPassword' })
  }
}
</script>

<style lang="less" scoped>
.head {
  .logo {
    display: flex;
    align-items: center;
    img {
      height: 36px;
    }
    .logo-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .goBefore {
    color: rgb(12, 52, 186);
  }
}
.login-box {
  padding: 0 20px;
  margin-top: 30%;
  .login-title {
    color: #666;
  }
  .login-subTitle {
    color: #666;
    font-size: 16px;
  }
  .login-tip {
    text-align: right;
    font-size: 14px;
    line-height: 30px;
    margin-top: 10px;
    margin-bottom: 40px;
    padding-right: 10px;
  }
  .popup-title {
    color: #666;
    font-size: 24px;
    padding: 10px;
    font-weight: bold;
  }
}
:deep(.van-field__label) {
  margin: 0;
}
</style>
